var airportFourCodeOption = [{id: 'CCDY', text: 'CCDY'}, {id: 'NSEF', text: 'NSEF'}, {id: 'QUGO', text: 'QUGO'}];
var ifUseOption = [{id: 'Y', text: '已启用'}, {id: 'N', text: '未启用'}];
var mTable;
var userDatatable;
var cityArray = [{id: ' ', text: ' '}];
var form;
var times = 0;
var oldProvince;
var msg;
var provinceId;
var searchTC = [];
var searchFC = [];
jQuery(document).ready(function () {
    userDatatableSource.init();
    pageSource.init();
    searchFormInit();
});

/**
 * 行内删除功能
 * @param id
 */
function deleteByPrefixAndNo(id) {
    layer.confirm('确认删除吗?', {
        btn: ['yes', 'no'] //可以无限个按钮
        , yes: function () {
            $.hcPostAjax({
                url: basePath + "/hcSysAirwatch/deleteById",
                data: {
                    'id': id

                },
                success: function () {
                    layer.msg('删除成功！', {
                        icon: 1, time: 1500
                    }, function () {
                        $("#m_search").click();
                    });
                }

            })


        }, btn2: function () {
            layer.msg('取消删除！', {
                icon: 1, time: 1500
            }, function () {
                $("#m_search").click();
            });
        }
    });
}

/**
 * 修改数据
 */
function EdiIt(id) {
    provinceId = id;
    msg = '编辑';
    openEditUser('修改机场维表信息', id);
}

/**
 * 已启用未启用小标签
 * @type {{Y: {title: string, class: string}, N: {title: string, class: string}}}
 */
const ifUseObj = {
    'Y': {
        title: "已启用",
        class: " m-badge--success"
    },
    'N': {
        title: "未启用",
        class: " m-badge--danger"
    }
};

/**
 * 表格列定义
 *
 * @type {*[]}
 */
var tableColumns = [
    {
        field: "id", title: "#", width: 20, textAlign: 'center',
        selector: {class: "m-checkbox--solid m-checkbox--brand"}
    },
    {
        field: "actions", title: "操作", width: 80, textAlign: 'center', titleHide: true, overflow: "visible",
        template: function (row) {
            var buttons = getColumnButton({
                clazz: 'm-btn--hover-accent editBtn',
                title: '编辑', icon: 'la la-edit',
                click: "EdiIt('" + row.id + "')"
            });

            buttons = buttons + getColumnButton({
                clazz: 'm-btn--hover-danger',
                title: '删除', icon: 'la la-trash',
                click: "deleteByPrefixAndNo('" + row.id + "')"
            });
            return buttons;
        }
    },
    {field: "airportThreeCode", title: "机场三字码", textAlign: 'center', sortable: false},
    {field: "airportFourCode", title: "机场四字码", textAlign: 'center', sortable: false},
    {field: "cname", title: "机场中文名称", textAlign: 'center', sortable: false},
    {field: "ename", title: "机场英文名称", textAlign: 'center', sortable: false},
    {field: "country", title: "机场所在国家", textAlign: 'center', sortable: false},
    {field: "province", title: "机场所在省份", textAlign: 'center', sortable: false},
    {field: "city", title: "机场所在城市", textAlign: 'center', sortable: false},
    {field: "taddress", title: "机场SITA电报地址", textAlign: 'center', sortable: false},
    {field: "longitude", title: "机场经度", textAlign: 'center', sortable: false},
    {field: "widthitude", title: "机场纬度", textAlign: 'center', sortable: false},
    {
        field: "ifUse", title: "是否启用", textAlign: 'center', sortable: false,
        template: function (t) {

       var state = "<input lay-ignore='true'  type='checkbox'  value='" + t.code + "' id='airlineStatus' lay-filter='airlineStatus' checked='checked' name='airlineStatus'  lay-skin='switch' lay-text='正常|停用' >";


            return state}
    },
    {field: "operator", title: "操作人", textAlign: 'center', sortable: false},
    {field: "operatorType", title: "操作类型", textAlign: 'center', sortable: false},
    {field: "operatorTime", title: "操作时间", textAlign: 'center', sortable: false},
    {field: "createTime", title: "创建时间", textAlign: 'center', sortable: false}
];

/**
 * 初始化表格定义
 */
var userDatatableSource = {
    init: function () {
        var params = {
            ifEffective: 0
        };
        userDatatable = $("#airportMaintenance_data").mDatatable(getMDatatableOption("list", params, tableColumns));
    },
    deleteById: function (ids) {
        $.hcPostAjax({
            showLoad: true,
            msgPrefix: '机场维表信息删除失败：',
            type: 'delete',
            url: basePath + '/hcSysAirwatch/' + ids,
            success: function (json) {
                layer.msg('机场维表信息删除成功！', {
                    icon: 1, time: 1500
                }, function () {
                    userDatatable.reload();
                });
            }
        });
    }
};

/**
 * 页面初始化
 * @type {{init: pageSource.init}}
 */
var pageSource = {
    init: function () {
        toUpperCase("#resetTC");
        toUpperCase("#resetFC");
        toUpperCase("#EdAirportThreeCode");
        toUpperCase("#EdAirportFourCode");
        toUpperCase("#taddress");
        checkEvents();//表单正则校验
        /**
         * 重置
         */
        $("#m_reset").on("click", function () {
            $("#resetTC").val('').change();
            $("#resetFC").val('').change();
            $("#resetCN").val('');
            $("#resetEN").val('');
            $("#resetIF").val('').change();
        });

        /**
         * 查询
         */
        $("#m_search").on("click", function () {
            var param = {
                airportThreeCode: $.trim($("select[name='airportThreeCode']").val()),
                airportFourCode: $.trim($("select[name='airportFourCode']").val()),
                cname: $.trim($("input[name='cname']").val()),
                ename: $.trim($("input[name='ename']").val()),
                ifUse: $.trim($("select[name='ifUse']").val()),
            };
            queryMDatatable(userDatatable, param);
            searchTC = [];
            searchFC = [];
            searchFormInit();
        });

        /**
         * 新增
         */
        $("#m_add").on("click", function () {
            openEditUser('新增机场维表信息', null);
        });

        /**
         * 修改数据
         */
        $("#editBtn").on("click", function () {
            var ids = getMDatatableSelectedIds(userDatatable);
            var id = ids[0];
            openEditUser('修改机场维表信息', id);
        });

        /**
         * 批量删除
         */
        $("#deleteBtn").on("click", function () {
            var ids = getMDatatableSelectedIds(userDatatable);
            if (ids.length === 0) {
                layer.msg('请勾选要删除的机场维表信息！', {
                    icon: 0
                });
                return;
            }
            var cname = getMDatatableSelectedColumns(userDatatable, "cname");
            layer.confirm('确定批量删除<font color="red">[' + cname + ']</font>机场维表信息？', {
                icon: 3,
                title: '提示',
                btn: ['确定', '取消'] // 按钮
            }, function () {
                userDatatableSource.deleteById(ids.join(','));
            }, function (index) {
                layer.close(index);
            });
        });

        $("#province").on('changeData', function (data) {
            console.log(data.elem); //得到select原始DOM对象
            console.log(data.value); //得到被选中的值
            console.log(data.othis); //得到美化后的DOM对象
        });
    }
}

/**
 * 表单校验
 */
function checkEvents() {
    form.verify({
        tCode: function (value, item) { // value：表单的值、item：表单的DOM对象
            if (!new RegExp("^[a-zA-Z]+$").test(value)) {
                return '用户名不能有特殊字符';
            }
            if (/(^\_)|(\__)|(\_+$)/.test(value)) {
                return '用户名首尾不能出现下划线\'_\'';
            }
            if (/^\d+\d+\d$/.test(value)) {
                return '用户名不能全为数字';
            }
        },
        // 我们既支持上述函数式的方式，也支持下述数组的形式
        // 数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]
        /*password: [
            /^[\S]{6,12}$/
            ,'密码必须6到12位，且不能出现空格'
        ]*/
        password: [
            /^.*(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?![.\n])(?!.*\s)^.{8,20}$/
            , '密码大于8位小于20位，必须包含大小写字母和数字'
        ],
        country: [
            /^[A-Z]{2}$/
            , '国家必须由两个大写字母组成'
        ],
        taddress: [
            /^[A-Z]{7}$/
            , '机场SITA电报地址必须由7位大写字母组成（前三个字母为地名,第4、5个字母为部门代码,后两个字母为公司代码）'
        ],
        airportThreeCode: [
            /^[A-Z]{3}$/
            , '机场三字码由三位大写字母组成'
        ],
        airportFourCode: [
            /^[A-Z]{4}$/
            , '机场四字码由四位大写字母组成'
        ],
        longitude: [
            /((^\d|^[0-9]\d|^1[0-7]\d)[\°\度](60|\d|[0-5]\d)[\'\′\分](60|\d|[0-5]\d)([″秒]|\'{2})[WE]{1}$)|(180[°度]0[\'′分]0([\"秒]|\'{2})[WE]$)/
            , '请输入正确的经度((88°43\'34\'\'E/W)/(88度43分34秒E/W))'
        ],
        widthitude: [
            /((^[0-8]{0,1}\d{1})[\°\度](60|\d|[0-5]\d)[\'\′\分](60|\d|[0-5]\d)([″秒]|\'{2})[NS]{1}$)|(90[°度]0[\'′分]0([\"秒]|\'{2})[NS]$)/
            , '请输入正确的纬度((88°43\'34\'\'S/N)/(88度43分34秒S/N))'
        ],
        ifUse: [
            /[YN]/
            , '是否使用只能是Y|N'
        ],
        cname: [
            /^[\一-\龥]{2,30}$/
            , '机场中文名称必须是中文'
        ]
    });
}

/**
 * 编辑下拉框设置
 */
function editFormInit() {
    $("#city").empty();
    $("#city").select2({
        placeholder: "机场所在城市",
        data: cityArray,
        allowClear: true
    });
    $.hcPostAjax({
        url: "../province/all",
        type: 'get',
        async: false,
        success: function (data) {
            var provinceArray = [];
            if (!isEmpty(data)) {
                $.each(data, function (i) {
                    var option = {id: data[i].pname + "", text: data[i].pname};
                    provinceArray.push(option);
                })
            }
            $("#province").select2({
                placeholder: "机场所在省份",
                data: provinceArray,
                allowClear: true
            });
        }
    });
    var pname = $("#province").val();
    $.hcPostAjax({
        url: '../province/getByPname?pname=' + pname,
        dataType: 'json',
        async: false,
        success: function (data) {
            if (!isEmpty(data)) {
                var pid = data[0].pid;
            }
            getCityList(pid);
        }
    });

    $.hcPostAjax({
        url: "../hcDicAgent/all",
        type: 'get',
        async: false,

        success: function (data) {
            if (!isEmpty(provinceId)) { //获取原来的对象
                var detail = getDetail(provinceId);
                //生成新的option
                var option = {id: detail.airportThreeCode, text: detail.airportThreeCode};
                var foption = {id: detail.airportFourCode, text: detail.airportFourCode};
                var optionArray = [];
                optionArray.push(option);
                airportFourCodeOption.push(foption);
            } else {
                var optionArray = [];
            }
            if (!isEmpty(data)) {
                $.each(data, function (i) {
                    var option = {id: data[i].agentcode + "", text: data[i].agentcode + "-" + data[i].namecn};
                    optionArray.push(option);
                })
            }
            $("#EdAirportThreeCode").select2({
                placeholder: "请输入或选择机场三字码",
                data: optionArray,
                allowClear: true,
                tags: true


            });
        }
    });

    $("#EdAirportFourCode").select2({
        placeholder: "请输入或选择机场四字码",
        data: airportFourCodeOption,
        allowClear: true,
        tags: true
    });

    $("#EdIfUse").select2({
        placeholder: "机场使用状态",
        data: ifUseOption,
        allowClear: true
    });
    EdiChange();
}

/**
 * 表单搜索
 */
function searchFormInit() {
    $.hcPostAjax({
        url: basePath + "/hcSysAirwatch/all",
        type: 'get',
        async: false,
        success: function (data) {

            if (!isEmpty(data)) {
                var TOption = [];
                var FOption = [];
                $.each(data, function (i) {
                    var option = {id: data[i].airportThreeCode + "", text: data[i].airportThreeCode + ""};
                    var fOption = {id: data[i].airportFourCode + "", text: data[i].airportFourCode + ""};
                    var tFlags = true;
                    var fFlags = true;
                    $.each(TOption, function (index) {
                        if (data[i].airportThreeCode == TOption[index].id) {
                            tFlags = false;
                        }
                    })

                    $.each(FOption, function (index) {
                        if (data[i].airportFourCode == FOption[index].id) {
                            fFlags = false;
                        }
                    })

                    if (tFlags) {
                        TOption.push(option);
                    } else {
                        tFlags = true;
                    }

                    if (fFlags) {
                        FOption.push(fOption);
                    } else {
                        fFlags = true;
                    }
                })
                searchTC = [];
                searchFC = [];
                searchTC = TOption;
                searchFC = FOption;
            }

        }
    })

    $("#resetTC").select2({
        placeholder: "机场三字码",
        data: searchTC,
        allowClear: true
    });
    $("#resetFC").select2({
        placeholder: "机场四字码",
        data: searchFC,
        allowClear: true
    });
    $("#resetIF").select2({
        placeholder: "是否启用",
        data: ifUseOption,
        allowClear: true
    });
}

/**
 * 新增和修改
 * @param title
 * @param obj
 */
function openEditUser(title, id) {

    var msg = isEmpty(id) ? "新增" : "编辑";

    layer.open({
        title: title,
        type: 1,
        maxmin: true,
        area: ['60%', '70%'],
        shadeClose: true,
        scrolling: false,
        content: $("#editHtml").html(),
        success: function (layero, index) {
            editFormInit();
            if (!isEmpty(id)) {
                renderFormData("#user-form", getDetail(id));
            }

            //保存
            $("#edit_yes").on("click", function () {
                times = 0;
                checkEvents();
                form.on('submit(save_airportmaintenance)', function (data) {
                    var param = getFormData("#user-form");
                    param.agentcode = $.trim($("select[name=agentcode]").val());
                    if (!isEmpty(id)) {
                        param.id = id;
                    } else {
                        param.password = $.trim($("input[name=password]").val());
                    }
                    $.hcPostAjax({
                        showLoad: true,
                        msgPrefix: msg + "出错：",
                        url: basePath + '/hcSysAirwatch/addAirportMaintenance',
                        data: param,
                        success: function (data) {
                            layer.msg('修改商品成功！', {
                                icon: 1, time: 1500
                            }, function () {
                                userDatatable.reload();
                                layer.closeAll();
                            });
                        }
                    });
                });
            });
            //取消修改
            $("#edit_cancle").on("click", function () {
                layer.closeAll();
                times = 0;
            });
        }
    });
}

/**
 * 数据回显
 * @param id
 * @returns {*}
 */
function getDetail(id) {
    var oldData;
    $.hcPostAjax({
        type: 'get',
        url: basePath + "/hcSysAirwatch/detail",
        data: {
            id: id
        },
        async: false,
        success: function (data) {
            oldData = data;
        }
    });
    return oldData;
}

/**
 *
 * 省市联动
 */
function provinceChange() {
    cityArray = [];
    var pname = $("#province").val();
    $("#city").empty();
    $.hcPostAjax({
        url: '../province/getByPname?pname=' + pname,
        dataType: 'json',
        async: false,
        success: function (data) {
            if (!isEmpty(data)) {
                var pid = data[0].pid;
            }

            //回显原来的旧数据
            if (msg == '编辑') {
                //获取原来的回显对象
                var airportMaintanance = getDetail(provinceId);
                //拿到city
                var oldCity = {id: airportMaintanance.city, text: airportMaintanance.city};
                //给推倒cityArray里面
                //清空cityArray
                cityArray = [];
                cityArray.push(oldCity);
                //刷新msg的值
                msg = '编辑只有一次';
            }

            getCityList(pid);
        }
    });
    $("#city").select2({
        placeholder: "机场所在城市",
        data: cityArray,
        allowClear: true
    });
}

/**
 *
 * 省市联动
 */
function EdiChange() {
    var pname = $("#province").val();
    if (isEmpty(pname)) {
        $("#city").empty();
        cityArray = [{id: ' ', text: ' '}];
    }
}

/**
 * 编辑
 * @param id
 */
function editFwb(id) {
    var ids = getMDatatableSelectedIds(userDatatable);
    let url = basePath + "/hcSysAirwatch/addorupdate?id=" + id
    layer.open({
        type: 2,
        area: ['100%', '100%'],
        content: url
    });
}

/**
 * 根据省份id获取城市列表
 * @param pid
 */
function getCityList(pid) {
    $.hcPostAjax({
        url: '../city/all?pid=' + pid,
        dataType: 'json',
        async: false,
        success: function (data) {
            if (!isEmpty(data)) {
                $.each(data, function (i) {
                    var option = {id: data[i].cname + "", text: data[i].cname};
                    //去除重复的选项
                    if (isEmpty(cityArray) || data[i].cname !== cityArray[0].id) {
                        cityArray.push(option);
                    }
                })
            }

        }
    });

    return cityArray;
}

/**
 * 实现下拉选择框的可选择可输入
 * @param inputId
 * @param selectId
 */
function selectOrInput(inputId, selectId) {
    var text = $("#" + selectId + "").text();
    var value = $("#" + selectId + "").val();
    $("#" + inputId + "").text(text);
    $("#" + inputId + "").val(value);

}

/**
 * 1、大小写转换，中文输入法下，仅在选词后触发input事件；
 * 2、光标定位
 * @type {boolean}
 */
function toUpperCase(option) {
    var typing = false;
    $(option).on('compositionstart', function () {
        typing = true;
    });
    $(option).on('compositionend', function () {
        typing = false;
        var fno = $(this).val();
        var start = this.selectionStart;
        var end = this.selectionEnd;
        $(this).val(fno.toUpperCase());
        this.setSelectionRange(start, end);
        return false;
    });
    $(option).on('input', function () {
        if (!typing) {
            var fno = $(this).val();
            var start = this.selectionStart;
            var end = this.selectionEnd;
            $(this).val(fno.toUpperCase());
            this.setSelectionRange(start, end);
        }
    });

    $(option).on('select', function () {
        if (!typing) {
            var fno = $(this).val();
            var start = this.selectionStart;
            var end = this.selectionEnd;
            $(this).val(fno.toUpperCase());
            this.setSelectionRange(start, end);
        }
    });

    $(option).on('select2', function () {
        if (!typing) {
            var fno = $(this).val();
            var start = this.selectionStart;
            var end = this.selectionEnd;
            $(this).val(fno.toUpperCase());
            this.setSelectionRange(start, end);
        }
    });

    $(option).on('search', function () {
        if (!typing) {
            var fno = $(this).val();
            var start = this.selectionStart;
            var end = this.selectionEnd;
            $(this).val(fno.toUpperCase());
            this.setSelectionRange(start, end);
        }
    });
}

